<template>
  <div class="factory-cust-chart factory-chart" :index="grpFlter.index">
    <div class="chart-handler" v-if="editable">
      <template v-if="!wrong && showList">
        <el-button type="primary" size="mini" @click="$emit('handleDeep')">深入分析</el-button>
      </template>
      <el-dropdown>
        <i class="el-icon-more"></i>
        <el-dropdown-menu slot="dropdown">
          <el-dropdown-item icon="el-icon-edit" @click.native="$emit('editChart')">
            编辑
          </el-dropdown-item>
          <el-dropdown-item icon="el-icon-close" @click.native="$emit('deleteChart')">
            删除
          </el-dropdown-item>
          <template v-if="!wrong">
            <el-dropdown-item @click.native="$emit('export')" class="drop-item">
              <icon-svg name="iconFacExport"></icon-svg>
              导出结果集
            </el-dropdown-item>
            <el-dropdown-item
              icon="el-icon-download"
              @click.native="$emit('downloadChart', { chart: chart, name: grpFlter.mainGrp.groupName })"
            >
              下载统计图
            </el-dropdown-item>
          </template>
        </el-dropdown-menu>
      </el-dropdown>
    </div>
    <el-row :gutter="50">
      <el-col :span="grpFlter.isCompare ? 12 : 24" v-loading="loading">
        <template v-if="!wrong">
          <div
            class="chart-content"
            :id="`factory-profile-${grpFlter.mainGrp.labId}-#${grpFlter.index}`"
            v-if="showList"
          ></div>
          <div class="chart-content no-record" v-else>
            <div class="chart-title">{{ grpFlter.mainGrp.groupName }}</div>
            <img src="~@/assets/img/no_profile.png" /> <br />
            暂无结果
          </div>
        </template>
        <div class="chart-content" v-else>
          <div class="chart-title">{{ grpFlter.mainGrp.groupName }}</div>
          <div class="no-record" v-if="!loading">
            <img src="~@/assets/img/no_records.png" /> <br />
            计算出错
          </div>
        </div>
      </el-col>
      <el-col :span="12" v-if="grpFlter.isCompare" v-loading="compare.loading">
        <template v-if="!compare.wrong">
          <div
            class="chart-content"
            :id="`factory-profile-compare-${grpFlter.mainGrp.labId}-#${grpFlter.index}`"
            v-if="compare.showList"
          ></div>
          <div class="chart-content no-record" v-else>
            <div class="chart-title">对比画像</div>
            <img src="~@/assets/img/no_profile.png" /> <br />
            暂无结果
          </div>
        </template>
        <div class="chart-content" v-else>
          <div class="no-record" v-if="!compare.loading">
            <div class="chart-title">对比画像</div>
            <img src="~@/assets/img/no_records.png" /> <br />
            计算出错
          </div>
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import * as echarts from 'echarts'
export default {
  props: {
    grpFlter: {
      type: Object,
      required: true,
      default: () => {}
    },
    editable: {
      type: Boolean,
      default: true
    },
    grpTotal: {
      // 客户数
      type: Object,
      default: () => {
        return {
          grpTotal: 0,
          compareTotal: 0
        }
      }
    }
  },
  data() {
    return {
      loading: false,
      pieChart: null,
      wrong: false,
      list: [],
      showList: true,
      compare: {
        loading: false,
        pieChart: null,
        wrong: false,
        list: [],
        showList: true
      }
    }
  },
  methods: {
    setLoading(type = 'default') {
      if (type === 'default') this.loading = true
      this.compare.loading = true
    },
    refreshChart(data = {}) {
      this.wrong = !!data.wrong
      this.list = data.labGrps || []
      this.showList = data.labGrps && data.labGrps.length > 0
      if (this.showList) {
        this.$nextTick(() => {
          if (!this.pieChart)
            this.pieChart = echarts.init(
              document.getElementById(`factory-profile-${this.grpFlter.mainGrp.labId}-#${this.grpFlter.index}`)
            )
          const _this = this
          let pieData = []
          let subText = []
          data.labGrps.forEach(item => {
            if (data.groupTyp !== 'enum' || (data.groupTyp === 'enum' && item.value !== 0)) {
              let label = item.desc || item.code
              if (Number(this.grpFlter.mainGrp.valueType) === 6 || Number(this.grpFlter.mainGrp.valueType) === 7) {
                label = label.replace(/-/g, ' -∞')
                label = label.replace(/[+]/g, ' +∞')
              }
              pieData.push({
                name: label,
                value: item.value
              })
            }
          })
          if (data.numLabGrps) {
            data.numLabGrps.forEach(numLab => {
              subText.push(`{a|${numLab.funcName}} ${numLab.funcResult}`)
            })
          }
          let option = {
            title: {
              text: this.grpFlter.mainGrp.groupName,
              textStyle: {
                fontSize: 16,
                fontWeight: 700
              },
              subtext: subText.join(' '),
              subtextStyle: {
                color: '#63708a',
                rich: {
                  a: {
                    padding: [5, 10],
                    lineHeight: 10,
                    color: '#63708a',
                    backgroundColor: '#f2f6ff',
                    borderRadius: 2
                  }
                }
              }
            },
            tooltip: {
              trigger: 'item',
              // formatter: '{b}<br/>数值：{c}<br/>占比：{d}%'
              formatter: function(params) {
                return (
                  params.name +
                  '<br />' +
                  '数值：' +
                  params.value +
                  '<br />' +
                  '占比：' +
                  ((params.value / _this.grpTotal.grpTotal) * 100).toFixed(2) +
                  '%'
                )
              }
            },
            series: [
              {
                type: 'pie',
                radius: this.grpFlter.mainGrp.graphType === 'pie' ? '65%' : ['45%', '70%'],
                startAngle: 20,
                top: '15%',
                data: pieData,
                label: {
                  normal: {
                    position: pieData.length >= 30 ? 'inner' : 'outter',
                    color: '#666'
                  }
                },
                labelLine: {
                  lineStyle: {
                    color: '#666'
                  }
                },
                itemStyle: {
                  color(params) {
                    // let colorList = ['#475fba', '#8bb4ff', '#ffab34', '#ffdc75', '#baaaf5', '#9983ea']
                    let colorList = ['#0f80ff', '#11ce98', '#f79e2a', '#7886c5', '#e8d318', '#4dad30', '#f3b177']
                    let r = Math.floor(Math.random() * 256)
                    let g = Math.floor(Math.random() * 256)
                    let b = Math.floor(Math.random() * 256)
                    return params.dataIndex > colorList.length - 1
                      ? 'rgb(' + r + ',' + g + ',' + b + ')'
                      : colorList[params.dataIndex]
                  }
                }
              }
            ],
            label: {
              formatter: function(params) {
                let label = params.name
                if (params.name.length >= 20) {
                  label = params.name.split('~')[0] + '~ \n ' + params.name.split('~')[1]
                }
                return label
              }
            }
          }
          this.pieChart.setOption(option, true)
          window.addEventListener('resize', () => {
            this.pieChart.resize()
          })
        })
      } else {
        if (this.pieChart) {
          this.pieChart.dispose()
          this.pieChart = null
        }
      }
      this.loading = false
    },
    refreshCompareChart(data = {}) {
      this.compare.wrong = !!data.wrong
      this.compare.list = data.labGrps || []
      let showList = data.labGrps && data.labGrps.length > 0
      if (this.compare.list.length) {
        let flag = false
        this.compare.list.forEach(item => {
          if (item.value > 0) flag = true
        })
        showList = flag
      }
      this.compare.showList = showList
      if (showList) {
        this.$nextTick(() => {
          this.compare.pieChart = echarts.init(
            document.getElementById(`factory-profile-compare-${this.grpFlter.mainGrp.labId}-#${this.grpFlter.index}`)
          )
          let pieData = []
          let subText = []
          data.labGrps.forEach(item => {
            let label = item.desc || item.code
            if (Number(this.grpFlter.mainGrp.valueType) === 6 || Number(this.grpFlter.mainGrp.valueType) === 7) {
              label = label.replace(/-/g, ' -∞')
              label = label.replace(/[+]/g, ' +∞')
            }
            pieData.push({
              name: label,
              value: item.value
            })
          })
          if (data.numLabGrps) {
            data.numLabGrps.forEach(numLab => {
              subText.push(`{a|${numLab.funcName}} ${numLab.funcResult}`)
            })
          }
          let option = {
            title: {
              text: this.grpFlter.mainGrp.groupName,
              textStyle: {
                fontSize: 16,
                fontWeight: 700
              },
              subtext: subText.join(' '),
              subtextStyle: {
                color: '#63708a',
                rich: {
                  a: {
                    padding: [5, 10],
                    lineHeight: 10,
                    color: '#63708a',
                    backgroundColor: '#f2f6ff',
                    borderRadius: 2
                  }
                }
              }
            },
            tooltip: {
              trigger: 'item',
              formatter: '{b}<br/>数值：{c}<br/>占比：{d}%'
            },
            series: [
              {
                type: 'pie',
                startAngle: 20,
                top: '15%',
                radius: this.grpFlter.mainGrp.graphType === 'pie' ? '70%' : ['45%', '70%'],
                data: pieData,
                label: {
                  normal: {
                    position: pieData.length >= 30 ? 'inner' : 'outter',
                    color: '#666'
                  }
                },
                labelLine: {
                  lineStyle: {
                    color: '#666'
                  }
                },
                itemStyle: {
                  color(params) {
                    const colorList = ['#0f80ff', '#11ce98', '#f79e2a', '#7886c5', '#e8d318', '#4dad30', '#f3b177']
                    let r = Math.floor(Math.random() * 256)
                    let g = Math.floor(Math.random() * 256)
                    let b = Math.floor(Math.random() * 256)
                    return params.dataIndex > colorList.length - 1
                      ? 'rgb(' + r + ',' + g + ',' + b + ')'
                      : colorList[params.dataIndex]
                  }
                }
              }
            ],
            label: {
              formatter: function(params) {
                let label = params.name
                if (params.name.length >= 20) {
                  label = params.name.split('~')[0] + '~ \n ' + params.name.split('~')[1]
                }
                return label
              }
            }
          }
          this.compare.pieChart.setOption(option, true)
          window.addEventListener('resize', () => {
            this.compare.pieChart.resize()
          })
        })
      } else {
        if (this.compare.pieChart) {
          this.compare.pieChart.dispose()
          this.compare.pieChart = null
        }
      }
      this.compare.loading = false
    }
  }
}
</script>

<style lang="scss">
@import './chart.scss';
</style>
